//
//  BaseCollectionViewController.m
//  德方军考通
//
//  Created by 毕武侠 on 16/8/27.
//  Copyright © 2016年 毕武侠. All rights reserved.
//

#import "BaseCollectionViewController.h"
#import "BaseCollectionViewCell.h"
#import "BaseCollectionModel.h"

@interface BaseCollectionViewController () <DZNEmptyDataSetSource, DZNEmptyDataSetDelegate, cellDidActionDelegate>

@property (nonatomic, assign) NSUInteger     pageNumber;
@property (nonatomic, getter=isLoading) BOOL loading;
@property (nonatomic, assign) BOOL isLoadNew;

@end

@implementation BaseCollectionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.emptyDataSetSource = self;
    self.collectionView.emptyDataSetDelegate = self;
    self.pageNumber = 1;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - set 

- (void)setSourceData:(NSMutableArray *)sourceData {
    _sourceData = sourceData;
    
    [self.collectionView reloadData];
}

- (void)setLoading:(BOOL)loading {
    if (self.isLoading == loading) {
        return;
    }
    
    _loading = loading;
    [self.collectionView reloadEmptyDataSet];
}

#pragma mark - get
- (NSString *)modelClass {
    if (!_modelClass) {
        _modelClass = @"BaseCollectionModel";
    }
    return _modelClass;
}

- (NSString *)titles {
    if (!_titles) {
        _titles = @"";
    }
    return _titles;
}

- (NSString *)message {
    if (!_message) {
        _message = @"";
    }
    return _message;
}

#pragma mark - init

- (void)initRefreshView {
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.pageNumber = 1;
        [self loadData];
    }];
    self.collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    self.collectionView.mj_footer.automaticallyHidden = YES;
    self.collectionView.mj_footer.automaticallyChangeAlpha = YES;
}

#pragma mark - network

- (void)loadData {
    if (self.parameter == nil) {
        [self.collectionView.mj_header endRefreshing];
        return;
    }
    
    [self.collectionView.mj_footer endRefreshing];
    NSMutableDictionary *data = [NSMutableDictionary dictionaryWithDictionary: self.parameter.body];
    data[@"page"] = [NSString stringWithFormat:@"%ld", self.pageNumber];
    self.parameter.body = data;
    
    [SGHttpTool POST:self.parameter sucess:^(id result) {
        SGReceive *receive = [SGReceive receiveWithResponseObject:result dataClass:NSClassFromString(self.modelClass)];
        if ([receive.code intValue] == 200) {
            NSMutableArray *data = receive.data;
            if ([data count] > 0) {
                self.pageNumber++;
                self.sourceData = data;
            }
        }
        [self.collectionView.mj_header endRefreshing];
    } failure:^(id reslut) {
        [self.collectionView.mj_header endRefreshing];
    }];
}

- (void)loadMoreData {
    if (self.parameter == nil) {
        [self.collectionView.mj_footer endRefreshing];
        return;
    }
    
    NSMutableDictionary *data = [NSMutableDictionary dictionaryWithDictionary: self.parameter.body];
    data[@"page"] = [NSString stringWithFormat:@"%ld", self.pageNumber];
    self.parameter.body = data;
    
    [SGHttpTool POST:self.parameter sucess:^(id result) {
        SGReceive *receive = [SGReceive receiveWithResponseObject:result dataClass:NSClassFromString(self.modelClass)];
        if ([receive.code intValue] == 200) {
            NSMutableArray *data = receive.data;
            
            if ([data count] > 0) {
                self.pageNumber++;
                [self.sourceData addObjectsFromArray:data];
                [self.collectionView reloadData];
                [self.collectionView.mj_footer endRefreshing];
            } else {
                [self.collectionView.mj_footer endRefreshingWithNoMoreData];
            }
        } else {
            [self.collectionView.mj_footer endRefreshing];
        }
    } failure:^(id reslut) {
        [self.collectionView.mj_footer endRefreshing];
    }];
}

- (void)reloadNewData {
    if (self.parameter == nil) {
        [self.collectionView.mj_header endRefreshing];
        self.loading = NO;
        if (self.sourceData.count == 0) {
            self.titles = @"暂无数据";
            [self.collectionView reloadEmptyDataSet];
        }
        return;
    }
    
    self.isLoadNew = self.loading = YES;
    
    self.pageNumber = 1;
    NSMutableDictionary *data = [NSMutableDictionary dictionaryWithDictionary: self.parameter.body];
    data[@"page"] = @"1";
    self.parameter.body = data;
    
    [SGHttpTool POST:self.parameter sucess:^(id result) {
        self.isLoadNew = self.loading = NO;
        SGReceive *receive = [SGReceive receiveWithResponseObject:result dataClass:NSClassFromString(self.modelClass)];
        if ([receive.code intValue] == 200) {
            NSMutableArray *data = receive.data;
            if (data.count > 0) {
                self.pageNumber++;
                [self.sourceData removeAllObjects];
                if (self.isDealData == YES) {
                    [self dealData:receive.data atPage:self.pageNumber - 1];
                } else {
                    self.sourceData = receive.data;
                }
            } else if (self.sourceData.count == 0) {
                self.titles = @"暂无数据";
                [self.collectionView reloadEmptyDataSet];
            }
        } else if (self.sourceData.count == 0) {
            self.titles = @"暂无数据";
            [self.collectionView reloadEmptyDataSet];
        }
        [self.collectionView.mj_header endRefreshing];
    } failure:^(id reslut) {
        self.isLoadNew = self.loading = NO;
        [self.collectionView.mj_header endRefreshing];
        if (self.sourceData.count == 0) {
            self.titles = NoNetWorkMessage;
            [self.collectionView reloadEmptyDataSet];
        }
    }];
}

- (void)refreshView {
    [self.collectionView reloadData];
    if (_sourceData.count == 0) {
        if (self.titles.length == 0) {
            self.titles = @"暂无数据";
        }
        [self.collectionView reloadEmptyDataSet];
    }
}

- (void)dealData:(id)data atPage:(NSUInteger)index {
    
}

#pragma mark <UICollectionViewDataSource>

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.sourceData.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    // Configure the cell
    BaseCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:self.identifier
                                                                             forIndexPath:indexPath];
    if (cell == nil) {
        cell = [[BaseCollectionViewCell alloc] init];
    }
    
    BaseCollectionModel *model = self.sourceData[indexPath.row];
    
    cell.count          = self.sourceData ? self.sourceData.count : 0;
    cell.indexPath      = indexPath;
    cell.actionDelegate = self;
    [cell bindModel:model];
    return cell;
}

#pragma mark <UICollectionViewDelegate>

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return self.minLineSpace;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return self.minInteritemSpace;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return  self.edgeInsets;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    BaseCollectionModel *model = self.sourceData[indexPath.row];
    return  model.cellSize;
}

#pragma mark - cell Action

- (void)actionIndexPath:(NSIndexPath *)indexPath infoData:(id)data {
    
}

#pragma mark - DZNEmptyDataSetSource Methods

- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *text = nil;
    UIFont *font = nil;
    UIColor *textColor = nil;
    
    NSMutableDictionary *attributes = [NSMutableDictionary new];
    
    text = self.titles;
    font = [UIFont systemFontOfSize:17.0];
    textColor = [UIColor grayColor];
    
    if (font) [attributes setObject:font forKey:NSFontAttributeName];
    if (textColor) [attributes setObject:textColor forKey:NSForegroundColorAttributeName];
    
    return [[NSAttributedString alloc] initWithString:text attributes:attributes];
}

- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [UIImage imageNamed:self.isLoading ? @"loading_imgBlue" : IMG_EmptyDefault];
}

- (CAAnimation *)imageAnimationForEmptyDataSet:(UIScrollView *)scrollView {
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform"];
    animation.fromValue = [NSValue valueWithCATransform3D:CATransform3DIdentity];
    animation.toValue = [NSValue valueWithCATransform3D: CATransform3DMakeRotation(M_PI_2, 0.0, 0.0, 1.0) ];
    animation.duration = 0.25;
    animation.cumulative = YES;
    animation.removedOnCompletion = NO;
    animation.fillMode = kCAFillModeForwards;
    animation.repeatCount = MAXFLOAT;
    
    return animation;
}

- (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView {
    return [UIColor whiteColor];
}

- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
    return -(SCREEN_HEIGHT / 6);
}

- (CGFloat)spaceHeightForEmptyDataSet:(UIScrollView *)scrollView {
    return 0.0;
}

#pragma mark - DZNEmptyDataSetDelegate Methods

- (BOOL)emptyDataSetShouldDisplay:(UIScrollView *)scrollView {
    return YES;
}

- (BOOL)emptyDataSetShouldAllowTouch:(UIScrollView *)scrollView {
    return NO;
}

- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    return YES;
}

// YES: 开始转圈
- (BOOL)emptyDataSetShouldAnimateImageView:(UIScrollView *)scrollView {
    return self.isLoading;
}

- (void)emptyDataSet:(UIScrollView *)scrollView didTapView:(UIView *)view {
    if (self.isLoading) {
        return;
    }
    
    self.loading = YES;
    [self reloadNewData];
}

- (void)emptyDataSet:(UIScrollView *)scrollView didTapButton:(UIButton *)button {
    if (self.isLoading) {
        return;
    }
    
    self.loading = YES;
    [self reloadNewData];
}

#pragma mark - View Auto-Rotation

- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskAll;
}

- (BOOL)shouldAutorotate
{
    return YES;
}

@end
